package com.sam.example2.adapter;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CalculatorHandler extends IoHandlerAdapter {
	private static final Logger LOGGER = LoggerFactory.getLogger(CalculatorHandler.class);

	private ScriptEngine jsEngine = null;

	public CalculatorHandler() {
		ScriptEngineManager sfm = new ScriptEngineManager();
		jsEngine = sfm.getEngineByName("JavaScript");
		if (jsEngine == null) {
			throw new RuntimeException("找不到 JavaScript 引擎。");
		}
	}

	public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
		LOGGER.warn(cause.getMessage(), cause);
	}

	/**
	 * messageReceived由IoHandler接口声明。当接收到新的消息的时候，该方法就会被调用
	 * 此处的逻辑是如果传入了“quit”，则通过session.close关闭当前连接；如果不是的话，就执行该表达式并把结果通过session.write发送回去。
	 * 将传入值，转化成javascript表达式，返回结果写入会话中
	 */
	public void messageReceived(IoSession session, Object message) throws Exception {
		String expression = message.toString();
		if ("quit".equalsIgnoreCase(expression.trim())) {
			session.close(true);
			return;
		}
		try {
			System.out.println(expression);
			Object result = jsEngine.eval(expression);
			session.write(result.toString());
		} catch (ScriptException e) {
			LOGGER.warn(e.getMessage(), e);
			session.write("Wrong expression, try again.");
		}
	}
}
